package com.ydlclass.loadbalancer.SelectorImpl;

import com.ydlclass.YrpcBootstrap;
import com.ydlclass.loadbalancer.Selector;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Map;

/**
 * 最短响应时间算法
 * @Author duWenJian
 * @Date 2024/2/27 10:55
 * @Version 1.0
 */
@Slf4j
public class MinimumResponseTimeSelector implements Selector {


    public MinimumResponseTimeSelector() {
    }

    @Override
    public InetSocketAddress getNext() {
        Map.Entry<Long, Channel> entry = YrpcBootstrap.ANSWER_TIME_CHANNEL_CACHE.firstEntry();
            if (entry!=null){
                if (log.isDebugEnabled()){
                    log.debug("最小响应时间负载均衡器获取到响应时间最小的节点：{},响应时间为{}",entry.getValue().remoteAddress(),entry.getKey());
                }
                if (log.isInfoEnabled()){
                    log.info("最小响应时间负载均衡器获取到响应时间最小的节点：{},响应时间为{}",entry.getValue().remoteAddress(),entry.getKey());
                }
                return (InetSocketAddress)entry.getValue().remoteAddress();
        }
        log.info("最小响应时间负载均衡器获取到响应时间最小的节点失败，使用默认负载均衡节点");
        Channel channel = (Channel)YrpcBootstrap.CHANNEL_CACHE.values().toArray()[0];
        return  (InetSocketAddress)channel.remoteAddress();
    }
}
